#include "extensionmanager.h"
#include "extension.h"
#include "extensiondeclaration.h"
#include "extensionfactory.h"

namespace yc {

ExtensionManager::ExtensionManager(ExtensionFactory* factory, QObject* parent)
    : QObject(parent), factory_(factory)
{
}

Extension* ExtensionManager::start(const ExtensionDeclaration& decl, CreatorProject* project,
                                   QWidget* container)
{
    Q_ASSERT(factory_);
    if (factory_ && decl.isValid()) {
        // 创建扩展
        if (Extension* e = factory_->create(this, decl, project, container)) {
            // 保存到列表
            extensions_.push_back(e);
            // 处理销毁信号
            connect(e, &Extension::destroyed, this,
                    [this](QObject* e) { extensions_.removeOne(static_cast<Extension*>(e)); });
            e->start(decl.startArgs());
            Q_EMIT started(e);
            return e;
        }
    }
    return nullptr;
}

void ExtensionManager::stop(Extension* e)
{
    Q_ASSERT(e);
    if (e) {
        e->disconnect(nullptr, this, nullptr);
        Q_EMIT aboutToBeStopped(e);
        e->stop();
        Q_ASSERT(factory_);
        factory_->destroy(e);
        extensions_.removeOne(e);
    }
}

void ExtensionManager::stopAll()
{
    while (!extensions_.empty()) {
        stop(extensions_.last());
    }
}

} // namespace yc
